<?php

namespace App\Admin\Controllers\Machine;

use App\Admin\Actions\Grid\Row\SwtMachine\MachineBindMerchant;
use App\Admin\Actions\Grid\Row\SwtMachine\MachineGoods;
use App\Admin\Actions\Grid\Row\SwtMachine\Replenish;
use App\Admin\Renderable\UserRenderable;
use App\Enums\SourceTypeEnum;
use App\Models\SwtBjMachine;
use App\Models\SwtDheMachine;
use App\Models\SwtMachine;
use App\Models\SwtMachineGood;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Models\Administrator;
use Illuminate\Validation\Rule;

class SwtMachineController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(SwtMachine::with('merchant_owner'), function (Grid $grid) {
            $grid->model()->orderBy('id','desc');

            $grid->column('id');
            $grid->column('qrcode') -> qrcode( function () {
                return config('app.url').'/api/swt/qrcode?mid='.$this->machine_no.'&doorId=1';
            });
            $grid->column('machine_name');
            $grid->column('machine_no');
            $grid->column('merchant_owner') -> display( function ($value) {
                $value = $value -> first();
                return empty($value) ? '-' : "<span class='label badge-info'>{$value -> name}</span>";
            });
            $grid->column('file_path') -> image('', 80,80) ;
            $grid->column('source_type') -> display( function ($value) {
                return SourceTypeEnum::getSourceTypeListDesc($value);
            });
            $grid->column('total_amount') -> display( function ($value) {
                return bcdiv($value, 100,2);
            });
            $grid->column('stock_out','缺货报警率') -> display( function ($value) {
                return bcmul($value, 100).'%';
            });
            $grid->column('sell_out','售罄报警率') -> display( function ($value) {
                return bcmul($value, 100).'%';
            });
            $grid->column('run_mode')->switch();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('machine_no');
                $filter->like('machine_name');
                $filter->equal('source_type') -> select(['本地','大黄鹅','宝坚']);
                $filter->like('merchant_owner.name','机主');
            });

            $grid->selector(function (Grid\Tools\Selector $selector) {
                $selector->selectOne('source_type', '厂家', [
                    0 => '其他',
                    1 => '大黄鹅',
                    2 => '宝坚'
                ]);
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->append(new MachineBindMerchant());
                $actions->append(new MachineGoods());
                $actions->append(new Replenish());
            });

            $grid->disableEditButton(false);

            $grid->disableDeleteButton(false);

            $grid->quickSearch(['machine_name','machine_no']);
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(SwtMachine::class, function (Form $form) {
            $form->display('id');

            $form -> disableViewButton();
            $form -> disableDeleteButton();

            $form->column(6, function (Form $form) {
                if($form -> isCreating()) {
                    $form -> text('machine_no')
                        -> rules(['required', Rule::unique('swt_machine') -> withoutTrashed()])
                        -> required();

                    $form -> radio('source_type')
                        -> options([ 2=>'宝坚' ])
                        -> default(2)
                        -> required();
                }

                $form -> text('machine_name')->required();
                if($form->model()->source_type == 2) {
                    $form->rate('stock_out', '缺货率')->required()->customFormat(function ($value) {
                        return bcmul($value, 100);
                    })->default(30);

                    $form->rate('sell_out', '售罄率')->required()->customFormat(function ($value) {
                        return bcmul($value, 100);
                    })->default(30);
                }

                $form -> switch('run_mode') -> default(1);

                $form -> textarea('address');
            });


            $form->column(6, function (Form $form) {

                $form -> image('file_path')
                    -> move('upload/machine')
                    -> uniqueName()
                    -> autoUpload();
                if($form->model()->source_type == 2) {
                    $form -> multipleSelectTable('replenish_users')
                        -> title('用户表')
                        -> from(UserRenderable::make())
                        -> model(Administrator::class, 'id', 'name');

                    $form -> multipleSelectTable('warning_users')
                        -> title('用户表')
                        -> from(UserRenderable::make())
                        -> model(Administrator::class, 'id', 'name');

                    $form -> multipleSelectTable('stock_out_users')
                        -> title('用户表')
                        -> from(UserRenderable::make())
                        -> model(Administrator::class, 'id', 'name');
                }
            });

            $form -> saving(function (Form $form) {
               $form -> stock_out /= 100;
               $form -> sell_out /= 100;
            });

            $form->deleting(function (Form $form) {
                $data = $form->model()->toArray();
                foreach($data as $v) {
                    switch($v['source_type'])
                    {
                        case 1:
                            SwtDheMachine::where('machine_id', $v['id']) -> update(['machine_id'=>null]);
                            break;
                        case 2:
                            $res = SwtMachineGood::where('machine_id', $v['id']) -> first();
                            if($res) {
                                return $form->response()->error('设备库存未清空');
                            } else {
                                SwtBjMachine::where('machine_id', $v['id']) -> update(['machine_id'=>null]);
                            }
                            break;
                    }
                }
            });
        });
    }
}
